<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require dirname(__FILE__).'/pc_controller.php';

class Api_activity extends PC_controller {

	public function __construct(){
		parent::__construct();
    $this->load->model('Apilogmodel','m_api_log');
    $this->load->model('Customermodel','m_customer');
    $this->load->model('Activitymodel','m_activity');
    $this->load->model('Templatemodel','m_template');
  }

  public function __destruct() {
      // $this->session->unset_userdata($this->_action);
      $customer = $this->session->userdata('activity_customer');
      $info = $this->input->post();
      $result = $this->response->getResult();
      $this->m_api_log->createApiLog(array(
          'ip_address' => $this->input->ip_address(),
          'customer_id' => empty($customer) ? 0 :  $customer['customer_id'],
          'openid' => isset($info['openid']) ? $info['openid'] : '',
          'request_uri' => $_SERVER['REQUEST_URI'],
          'post_data' => json_encode($info,JSON_UNESCAPED_UNICODE),
          'result_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
          'api_log_time_create' => NOW,
          // 'terminal' => TERMINAL_WEIXIN,
      ));
      $this->db->close();
  }

  public function getHb() {
    $this->validate->setRule('openid','string');
    $this->validate->setRule('openid_md5','string');
    $this->validate->setRule('activity','string');
    $this->validate->setRule('code','string');
    $this->validate->setRule('city','string');
    if(!$this->validate->run($this->input->post())){
      $this->response->setDetail($this->validate->getMessage());
      $this->response->responseExit();
    }
    $info = $this->validate->getResult();

    if(md5($info['openid'].SALF_CODE) !== $info['openid_md5']) {
        $this->response->setDetail('请勿恶意访问');
        $this->response->responseExit();
    }

    if($info['city'] != '邵阳') {
      $this->response->setDetail('邵阳地区才可以!');
      $this->response->responseExit();
    }

    $activity = $this->m_activity->getActivityByCode($info['activity']);
    if(empty($activity)) {
      $this->response->setDetail('非法访问!');
      $this->response->responseExit();
    }
    $activity_url = $this->m_activity->getActivityUrlByCode($info['code']);
    if(empty($activity_url)) {
      $this->response->setDetail('非法访问!!');
      $this->response->responseExit();
    }

    if($activity['activity_id'] != $activity_url['activity_id']) {
      $this->response->setDetail('非法访问!!!');
      $this->response->responseExit();
    }

    if($activity_url['activity_url_status'] != STATUS_PENDING) {
      $this->response->setDetail('该抽奖地址已使用!!!');
      $this->response->responseExit();
    }

    $template = $this->m_template->getTemplate($activity['template_id']);
    if(empty($template) || $template['template_status'] == STATUS_DELETE) {
        $this->response->setDetail('非法访问!!!!');
        $this->response->responseExit();
    }

    $this->load->library('rest');
    $token = file_get_contents(base_url('/symj/token/getAccessToken.php'));
    $result = json_decode(json_encode($this->rest->get('https://api.weixin.qq.com/cgi-bin/user/info'
              ,array('access_token' => $token,'openid' => $info['openid'],'lang' => 'zh_CN'))),true);
    if(!(isset($result['subscribe']) && $result['subscribe'] == 1)) {
      $this->response->setDetail('还未关注!!!');
      $this->response->responseExit();
    }
    $customer = $this->m_customer->getCustomerByOpenid($info['openid']);
    if(empty($customer)) {
      $result['customer_time_subscribe'] = date('Y-m-d H:i:s',$result['subscribe_time']);
      $result['tagid_list'] = json_encode($result['tagid_list'],JSON_UNESCAPED_UNICODE);
      $result['customer_time_create'] = NOW;
      $customer_id = $this->m_customer->createCustomer($result);
      if($customer_id == 0) {
        $this->response->setDetail('出现错误，请重试!');
        $this->response->responseExit();
      }
      $customer = $this->m_customer->getCustomer($customer_id);
    }
    $this->session->set_userdata('activity_customer',$customer);

    if($this->m_activity->checkActivityJoin($customer['customer_id'], $activity['activity_id'])) {
      $this->response->setDetail('你已参加此活动!');
      $this->response->responseExit();
    }

    include dirname(BASEPATH)."/symj/wxHongBao/oauth2.php";

    $wxapi=new Wxapi();

    $key=SALF_CODE;
    $openid = $info['openid'];//接收红包用户的openid    必须参数
    $openid_md5 = md5($info['openid'].$key); //接收红包用户的openid的md5校验码   必须参数
    $db = intval($template['template_money'] * 100); //红包金额,单位分  必须参数
    $db_md5 = md5($db.$key); //红包金额md5校验码   必须参数
    $send_name = $template['template_support']; //提供方名称   必须参数
    $wishing = $template['template_wish'];//红包祝福语   必须参数

    $result = ONLINE ? json_decode(json_encode($wxapi->pay($openid, $db, $send_name, $wishing)),true) : array("err_code" => 'SUCCESS',"status" => 'off');
    if($result['err_code'] != 'SUCCESS') {
      $this->response->setDetail($result['err_code_des']);
      $this->response->setAddon(array(
        'result' => $result,
      ));
  		$this->response->responseExit();
    }
    $data = array(
      'customer_id' => $customer['customer_id'],
      'openid' => $customer['openid'],
      'history_money' => $template['template_money'],
      'history_support' => $template['template_support'],
      'history_wish' => $template['template_wish'],
      'history_name' => $template['template_name'],
    );
    $data['history_result'] = json_encode($result);
    $data['history_time_create'] = NOW;
    $data['user_id'] = $this->m_app->getCurrentUserId();

    $history_id = $this->m_customer->createHistory($data);

    $this->m_activity->editActivityUrl(array(
      'activity_url_id' => $activity_url['activity_url_id'],
      'customer_id' => $customer['customer_id'],
      'history_id' => $history_id,
      'activity_url_status' => STATUS_ACTIVE,
      'activity_url_time_use' => NOW,
    ));

    $this->response->setSuccess();
    $this->response->setAddon(array(
      'money' => $template['template_money'],
    ));
		$this->response->responseExit();
  }

	public function getWxInfo() {
		$info = $this->input->get();
		$this->load->library('rest');
    $token = file_get_contents(base_url('/symj/token/getAccessToken.php'));
    $result = json_decode(json_encode($this->rest->get('https://api.weixin.qq.com/cgi-bin/user/info'
              ,array('access_token' => $token,'openid' => $info['openid'],'lang' => 'zh_CN'))),true);
		echo json_encode($result);
		exit();
	}

	public function testEmoji() {
		$this->load->library('rest');
    $token = file_get_contents(base_url('/symj/token/getAccessToken.php'));
    $result = json_decode(json_encode($this->rest->get('https://api.weixin.qq.com/cgi-bin/user/info'
              ,array('access_token' => $token,'openid' => 'oc0Pqv3MoMgfWgiZSaLZVfRPF0PE','lang' => 'zh_CN'))),true);
		$m = $this->m_customer->editCustomer(array(
			'customer_id' => 13,
			'nickname' => '邝利军1'.$result['nickname'],
		));
		$this->response->setSuccess();
		$this->response->setDetail($this->db->last_query());
		$this->response->setAddon($m);
		$this->response->responseExit();
	}

	public function syncWeixin(){
		$this->m_customer->sysnCustomerFromWx(true);

		$this->response->setSuccess();
		$this->response->responseExit();
	}
}
/* End of file home.php */
/* Location: ./application/controllers/home.php */
